import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import json
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score
from sklearn.preprocessing import OneHotEncoder
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from keras.models import Sequential
from keras.layers import Dense, Input
def check_field(row, field_name):
    return field_name in row['delivery_setting']
xls = pd.ExcelFile('C:/Users/zlsjBIDF/Downloads/例子.xlsx')
df = pd.read_excel(xls)
df_cleaned = df.dropna(subset=['delivery_setting'])
df_cleaned =df_cleaned[df_cleaned['click_cnt']/df_cleaned['show_cnt']>=0.1]
i = 0
data_names = ['landing_type', 'ad_type', 'is_comment_disable', 'ad_download_status']
data = df_cleaned[data_names]

df_encoded = pd.get_dummies(data, columns=['landing_type', 'ad_type', 'is_comment_disable', 'ad_download_status'])
df_encoded= df_encoded.fillna(0)
data = df_encoded.values

data_deliveries = [json.loads(json_str) for json_str in df_cleaned['delivery_setting'].values]
# 步骤1：确定所有唯一的键
keys = set(k for d in data_deliveries for k in d.keys())
keys_to_remove = ['end_time', 'start_time','schedule_time']
filtered_keys = ['bid_speed', 'bid_type', 'budget_mode', 'deep_bid_type', 'schedule_type', 'filter_night_switch', 'project_custom', 'budget_optimize_switch']
values_list = []
for i, delivery in enumerate(data_deliveries):
    row_values = []
    for k in filtered_keys:
        if k in delivery:
            row_values.append(delivery[k])
        else:
            # 键不存在时的处理方式，例如使用 None 或者默认值
            row_values.append(None)
    values_list.append(row_values)
print(filtered_keys)
y = np.array(values_list)

y = pd.DataFrame(y, columns=['bid_speed', 'bid_type', 'budget_mode', 'deep_bid_type', 'schedule_type', 'filter_night_switch', 'project_custom', 'budget_optimize_switch'])
y = pd.get_dummies(y, columns=['bid_speed', 'bid_type', 'budget_mode', 'deep_bid_type', 'schedule_type', 'filter_night_switch', 'project_custom', 'budget_optimize_switch'])
print(y.columns)
y = y.values

X_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.2, random_state=42)
model = Sequential()
model.add(Dense(64, input_dim=9, activation='relu'))  # 输入层和第一个隐藏层
model.add(Dense(32, activation='relu'))                # 第二个隐藏层
model.add(Dense(13, activation='sigmoid'))

# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
           # 输出层

model.summary()
# 训练模型
history=model.fit(X_train, y_train, epochs=20, batch_size=10, verbose=1)
# 提取训练和验证的loss
train_loss = history.history['loss']


# 绘制loss曲线
plt.figure(figsize=(10, 5))

plt.plot(train_loss, label='Training Loss')


plt.title('Training and Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.show()

y_pred_proba = model.predict(X_test)  # 这将是一个包含多个概率数组的列表

# 阈值化以得到0或1，假设y_pred_proba是一个列表
y_pred = [(prob > 0.5).astype(int) for prob in y_pred_proba]
print(y_pred)
print(data.shape)
print(y.shape)